var data = require("./data.js");
var clickjs = require("./click.js");
var mousejs = require("./mouse.js");

var define = data.define;

var traps = [];

function createTrap(map, mapW, mapH, width, mapMouse) {
  if (!clickjs.canInput(map, mapW, mapH, width, mapMouse))
    return;

  var t = {};
  t.x = parseInt(clickjs.getX());
  t.y = parseInt(clickjs.getY());
  t.times = 0;

  traps.push(t);
  showTrap(t, map, mapW, mapH, width, mapMouse);
}

function showTrap(b, map, mapW, mapH, width, mapMouse) {
  map[b.x][b.y] = define.TRAP;
}

function clearTrap(b, map, mapW, mapH, width, mapMouse) {
  map[b.x][b.y] = 0;
}

function detectMouse(b, map, mapW, mapH, width, mapMouse) {
  if (mapMouse[b.x][b.y] != -1) {
    mousejs.delete_mouse(mapMouse[b.x][b.y], map, mapW, mapH, width, mapMouse);
    console.log("trap mouse!");
    return true;
  }
  return false;
}

function updateTraps(map, mapW, mapH, width, mapMouse) {
  var temp = [];
  for (var i = 0; i < traps.length; i++) {
    traps[i].times++;
    if (traps[i].times >= (define.WapTrapTime / define.ShowDelay) || detectMouse(traps[i], map, mapW, mapH, width, mapMouse)) {
      clearTrap(traps[i], map, mapW, mapH, width, mapMouse);
      continue;
    }
    else {
      showTrap(traps[i], map, mapW, mapH, width, mapMouse);
      temp.push(traps[i]);
    }
  }
  traps = temp;
}

function getNum() {
  return traps.length;
}

function clear() {
  traps = [];
}

function getInfo() {
  return traps;
}

module.exports = {
  createTrap: createTrap,
  updateTraps: updateTraps,
  getNum: getNum,
  clear: clear,
  getInfo: getInfo
}